﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using WCBG.ToolsForUnity.Tools;


public class ClickReceiver : BaseTrackHolder
{

    public ReceiverBaseMono receiverObj;

    protected override void Start()
    {
        base.Start();
        
        UpdateEffectActive(false);
    }

    public override void OnRaycast(string eventID)
    {
        OnClick(eventID);
    }

    protected override void OnPlay()
    {
        UpdateEffectActive(true);
        transform.position = clipInfo.clickPosition;

        if (clipInfo.receiverMono != null)
        {
            receiverObj = GameObject.Instantiate(clipInfo.receiverMono);
            receiverObj.transform.SetParent(transform.parent);
            receiverObj.Initialize(TimelineID);
        }
    }

    protected override void OnPause()
    {
        base.OnPause();

        if (receiverObj != null)
        {
            GameObject.Destroy(receiverObj.gameObject);
            receiverObj = null;
        }
    }

    private void OnClick(string eventID)
    {
        UpdateEffectActive(false);
        if (clipInfo.isResumeTimeline)
        {
            ResumeTimeline();
        }
        if (receiverObj != null)
        {
            receiverObj.OnClick();
        }

        PlayClipAudio();
        EventBus.Instance.BroadCastEvent<string>(EventID.ON_TIMELINE_CLICK_EVENT, eventID);
    }

    private void UpdateEffectActive(bool value)
    {
        boxCollider.enabled = value;
        if (transform.childCount > 0)
        {
            for (int i = 0; i < transform.childCount; i++)
                transform.GetChild(i).SetActive(value);
        }
    }

    private void PlayClipAudio()
    {
        if (!string.IsNullOrEmpty(clipInfo.audioName))
        {
            this.PlayAudioEx(GetComponent<TLIdentifyHolder>().GetAudioPath() + clipInfo.audioName);
        }
    }


}
